/**
 * 妙趣拾光锦盒客户端全局脚本
 */

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    initTooltips();
    
    // 初始化返回顶部按钮
    initBackToTop();
    
    // 初始化抽盒动画
    initDrawAnimation();
    
    // 添加到购物车动画
    initAddToCartAnimation();
    
    // 初始化商品预览
    initProductPreview();
});

/**
 * 初始化Bootstrap工具提示
 */
function initTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

/**
 * 初始化返回顶部按钮
 */
function initBackToTop() {
    const backToTopButton = document.getElementById('backToTop');
    if (!backToTopButton) return;
    
    // 监听滚动事件
    window.addEventListener('scroll', function() {
        if (window.scrollY > 300) {
            backToTopButton.style.display = 'block';
        } else {
            backToTopButton.style.display = 'none';
        }
    });
    
    // 点击返回顶部
    backToTopButton.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

/**
 * 初始化抽盒动画
 */
function initDrawAnimation() {
    const drawButton = document.getElementById('drawBoxButton');
    if (!drawButton) return;
    
    drawButton.addEventListener('click', function(event) {
        event.preventDefault();
        
        // 显示抽盒动画
        const animationContainer = document.getElementById('drawAnimationContainer');
        if (animationContainer) {
            animationContainer.style.display = 'flex';
            document.getElementById('drawForm').style.display = 'block'; // 保持表单可见
            
            // 动画结束后隐藏动画并提交表单
            setTimeout(() => {
                animationContainer.style.display = 'none'; // 先隐藏动画
                document.getElementById('drawForm').submit(); // 再提交表单
            }, 1500);
        } else {
            // 如果没有动画容器，直接提交表单
            document.getElementById('drawForm').submit();
        }
    });
}

/**
 * 初始化添加到购物车动画
 */
function initAddToCartAnimation() {
    const addToCartButtons = document.querySelectorAll('.add-to-cart-btn');
    
    addToCartButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            // 获取商品图片位置
            const boxCard = this.closest('.box-card');
            if (!boxCard) return;
            
            const boxImage = boxCard.querySelector('.box-image');
            if (!boxImage) return;
            
            // 获取购物车图标位置
            const cartIcon = document.querySelector('.navbar .fa-shopping-cart');
            if (!cartIcon) return;
            
            // 创建飞向购物车的动画元素
            const flyingImage = document.createElement('img');
            flyingImage.src = boxImage.src;
            flyingImage.style.position = 'fixed';
            flyingImage.style.zIndex = '9999';
            flyingImage.style.width = '50px';
            flyingImage.style.height = '50px';
            flyingImage.style.borderRadius = '50%';
            flyingImage.style.objectFit = 'cover';
            
            // 获取图片和购物车的位置
            const imgRect = boxImage.getBoundingClientRect();
            const cartRect = cartIcon.getBoundingClientRect();
            
            // 设置初始位置
            flyingImage.style.left = `${imgRect.left}px`;
            flyingImage.style.top = `${imgRect.top}px`;
            
            // 添加到文档
            document.body.appendChild(flyingImage);
            
            // 动画持续时间
            const animationDuration = 800;
            const startTime = performance.now();
            
            // 动画函数
            function animate(currentTime) {
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / animationDuration, 1);
                
                // 贝塞尔曲线动画
                const x = imgRect.left + (cartRect.left - imgRect.left) * progress;
                const y = imgRect.top + (cartRect.top - imgRect.top - 100) * progress + Math.sin(progress * Math.PI) * 100;
                
                // 缩小效果
                const scale = 1 - 0.5 * progress;
                
                flyingImage.style.transform = `translate3d(0, 0, 0) scale(${scale})`;
                flyingImage.style.left = `${x}px`;
                flyingImage.style.top = `${y}px`;
                flyingImage.style.opacity = 1 - progress;
                
                if (progress < 1) {
                    requestAnimationFrame(animate);
                } else {
                    // 动画结束，移除元素
                    document.body.removeChild(flyingImage);
                    
                    // 更新购物车计数
                    const cartCountBadge = document.querySelector('.navbar .fa-shopping-cart + .badge');
                    if (cartCountBadge) {
                        const currentCount = parseInt(cartCountBadge.textContent) || 0;
                        cartCountBadge.textContent = currentCount + 1;
                        cartCountBadge.style.display = 'inline';
                    }

                    // 在加入购物车的点击事件处理函数中添加
                    trackEvent('add_to_cart', {
                        product_id: boxCard.dataset.boxId || '',
                        product_name: boxCard.querySelector('.card-title')?.innerText || '未知商品'
                    });
                }
            }
            
            requestAnimationFrame(animate);
        });
    });
}

/**
 * 初始化商品预览
 */
function initProductPreview() {
    const previewButtons = document.querySelectorAll('[data-product-preview]');
    
    previewButtons.forEach(button => {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            
            const productId = this.getAttribute('data-product-id');
            if (!productId) return;
            
            // 显示加载中
            const modal = new bootstrap.Modal(document.getElementById('productPreviewModal'));
            const modalBody = document.querySelector('#productPreviewModal .modal-body');
            
            modalBody.innerHTML = '<div class="text-center py-5"><div class="spinner-border text-primary" role="status"></div><p class="mt-2">加载中...</p></div>';
            modal.show();
            
            // 发起AJAX请求获取商品信息
            fetch(`/blindbox/api/product/${productId}/`, {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络错误');
                }
                return response.json();
            })
            .then(data => {
                // 更新模态框内容
                modalBody.innerHTML = `
                    <div class="row">
                        <div class="col-md-5">
                            <img src="${data.image_url || '/static/images/no-image.png'}" 
                                 alt="${data.name}" 
                                 class="img-fluid rounded">
                        </div>
                        <div class="col-md-7">
                            <h4>${data.name}</h4>
                            <p class="text-muted">${data.category || '未分类'}</p>
                            
                            <div class="mb-3">
                                <span class="badge bg-info">${data.brand || '未知品牌'}</span>
                                <span class="badge bg-secondary">${data.weight || '未知规格'}</span>
                            </div>
                            
                            <div class="d-flex align-items-center mb-3">
                                <span class="fs-4 text-danger me-2">¥${data.original_price || '0.00'}</span>
                            </div>
                            
                            ${data.expiry_date ? `<p class="mb-1"><small>有效期至: ${data.expiry_date}</small></p>` : ''}
                        </div>
                    </div>
                `;
            })
            .catch(error => {
                modalBody.innerHTML = `<div class="alert alert-danger">加载失败: ${error.message}</div>`;
            });
        });
    });
} 